package Comprehensive_04;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test6 {
    public static void main(String[] args) {
        Random rand = new Random();
        ArrayList<String> prise = new ArrayList<>();
        Collections.addAll(prise,"苹果 手机","华为手机","三洋踏板摩托","迪拜7日游","苹果笔记本",
                "联想笔记本","小米空气净化器","格力空调","海尔冰箱","海信电视");
        Lock lock = new ReentrantLock();
        Condition conA = lock.newCondition();
        Condition conB = lock.newCondition();
        Thread t1 = new Thread(() -> {
            while (true){
                try {
                    lock.lock();
                    int size = prise.size();
                    if (size == 0){
                        conA.signal();
                        conB.signal();
                        break;
                    }
                    int index = rand.nextInt(size);
                    System.out.println(Thread.currentThread().getName() + "...抽出了一个..." + prise.get(index));
                    prise.remove(index);
                    conB.signal();
                    conA.await();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        },"第一组");
        Thread t2 = new Thread(() -> {
            while (true){
                try {
                    lock.lock();
                    int size = prise.size();
                    if (size == 0){
                        conA.signal();
                        conB.signal();
                        break;
                    }
                    int index = rand.nextInt(size);
                    System.out.println(Thread.currentThread().getName() + "...抽出了一个..." + prise.get(index));
                    prise.remove(index);
                    conA.signal();
                    conB.await();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        },"第二组");
        t1.start();
        t2.start();
    }
}
